package com.zjp.mg.core;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.zjp.mg.config.ConnectionConfiguration;
import com.zjp.mg.model.ConnectionInformation;
import com.zjp.mg.util.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 请求
public class RequestDynamicMongoDBDataBaseImpl implements DynamicMongoDBDataBase, InitializingBean {

    public static final Logger log = LoggerFactory.getLogger(RequestDynamicMongoDBDataBaseImpl.class);


    static Map<String, MongoTemplate> mongoTemplateMap = new ConcurrentHashMap<>();


    public static final String REQUEST_PREFIX = "requestPrefix";

    ConnectionConfiguration connectionConfiguration;

    public RequestDynamicMongoDBDataBaseImpl(ConnectionConfiguration connectionConfiguration) {
        this.connectionConfiguration = connectionConfiguration;
    }

    public MongoTemplate getMongoTemplate() {
        HttpServletRequest request = ServletUtils.getRequest();
        String header = request.getHeader(REQUEST_PREFIX);
        Assert.hasText(header, "无效的请求头--requestPrefix");
        MongoTemplate mongoTemplate = mongoTemplateMap.get(header);
        Assert.notNull(mongoTemplate, "无效的mongoTemplate--mongoTemplate");
        return mongoTemplate;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        // 连接信息
        Map<String, ConnectionInformation> mapProperty = connectionConfiguration.getDataMap();
        for (Map.Entry<String, ConnectionInformation> entry : mapProperty.entrySet()) {
            ConnectionInformation value = entry.getValue();
            String uri = value.getUri();
            String databaseKey = value.getDatabase();
            MongoClient client = MongoClients.create(uri);
            MongoDatabase database = client.getDatabase(databaseKey);
            MongoTemplate mongoTemplate = new MongoTemplate(client, database.getName());
            log.info("==={}==={}===", uri, databaseKey);
            mongoTemplateMap.put(databaseKey, mongoTemplate);
        }
    }

    @Override
    public MongoTemplate getMongo() {
        return getMongoTemplate();
    }
}
